package com.bestcem.xm.ticket.util;

import cn.hutool.core.lang.ObjectId;
import cn.hutool.core.lang.Validator;
import com.alibaba.fastjson.JSONObject;
import com.bestcem.xm.ticket.controller.param.NotificationParam;
import com.bestcem.xm.ticket.dao.NotificationDao;
import com.bestcem.xm.ticket.entity.mongo.Notification;
import com.bestcem.xm.ticket.enums.NotificationTypeEnum;
import com.bestcem.xm.ticket.grpc.client.TicketAwardGrpcService;
import com.bestcem.xm.ticket.grpc.client.TicketBaseQdesGrpcService;
import com.bestcem.xm.ticket.grpc.client.TicketBaseSurveyGrpcService;
import com.bestcem.xm.ticket.grpc.client.TicketBaseUserGrpcService;
import com.bestcem.xm.ticket.grpc.client.dto.qdes.QdesDTO;
import com.bestcem.xm.ticket.grpc.client.dto.qdes.QuotaDTO;
import com.bestcem.xm.ticket.grpc.client.dto.survey.QuotaCheckItemDTO;
import com.bestcem.xm.ticket.grpc.client.dto.survey.QuotaConditionDTO;
import com.bestcem.xm.ticket.grpc.client.dto.user.SmtpDTO;
import com.bestcem.xm.ticket.service.dto.user.EmailContentDTO;
import com.bestcem.xm.ticket.service.manager.notification.WechatPublicManager;
import com.bestcem.xm.ticket.service.manager.notify.NotifyManager;
import com.bestcem.xm.ticket.task.NotificationTask;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Nullable;
import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 通知工具类
 *
 * @author gy.liu
 * @version 通知提醒新增微信公众号需求
 * @date 2021/8/24 17:36
 **/
@Slf4j
@Component
public class NotificationUtil {

    @Resource
    private NotificationDao notificationDao;

    @Resource
    private NotificationTask notificationTask;

    @Resource
    private TicketBaseQdesGrpcService ticketBaseQdesGrpcService;

    @Resource
    private TicketBaseUserGrpcService ticketBaseUserGrpcService;

    @Resource
    private TicketAwardGrpcService ticketAwardGrpcService;

    @Resource
    private TicketBaseSurveyGrpcService ticketBaseSurveyGrpcService;

    @Resource
    private WechatPublicManager wechatPublicManager;

    /**
     * 协议配置
     */
    @Value("${app.ticket.notify-protocol:http}")
    private String notifyProtocol;
    /**
     * 服务器配置
     */
    @Value("${app.ticket.notify-url:xm-test.bestcem.com}")
    private String notifyUrl;
    /**
     * 项目名字
     */
    @Value("${app.xm.name:倍市得CEM}")
    private String xmName;


    @Resource
    private NotifyManager notifyUtil;

    // 周期类型的通知 通知时间
    private static Map<String, Integer> PERIOD_NOTIFICATION_TIME = new HashMap<>();
    // 时间操作符
    public static final Map<String, String> TIME_OPERATOR_2_TXT = new HashMap<>();
    // 比较操作符
    public static Map<String, String> COMPARE_OPERATOR_2_TXT = new HashMap<>();

    static {
        PERIOD_NOTIFICATION_TIME.put("hour", 9);
        PERIOD_NOTIFICATION_TIME.put("minute", 0);
        PERIOD_NOTIFICATION_TIME.put("second", 0);
    }

    static {
        TIME_OPERATOR_2_TXT.put("day", "昨日");
        TIME_OPERATOR_2_TXT.put("week", "上周");
        TIME_OPERATOR_2_TXT.put("month", "上月");
    }

    static {
        COMPARE_OPERATOR_2_TXT.put("gt", "大于");
        COMPARE_OPERATOR_2_TXT.put("lt", "小于");
        COMPARE_OPERATOR_2_TXT.put("eq", "等于");
    }

    /**
     * 更新notification
     *
     * @param surveyId
     * @param params
     * @return Long
     * @author gy.liu
     * @date 2021/8/25
     * @date 2022/4/7 12:16 XiaoYunSong 通知提醒新增微信公众号需求 新增 是否开启免打扰/是否开启微信公众号通知
     */
    public Long updateNotification(String surveyId, NotificationParam params) {
        if (StringUtils.isEmpty(surveyId)) {
            log.error("[Ticket] updateNotification 缺少必要参数");
            return null;
        }

        Notification notification = new Notification();
        notification.setSurveyId(surveyId);
        if (Objects.nonNull(params.getRule())) {
            notification.setRule(NotificationParam.ruleToEntityRule(params.getRule()));
        }
        if (Objects.nonNull(params.getWays())) {
            notification.setWays(NotificationParam.wayToEntityWay(params.getWays()));
        }
        if (Objects.nonNull(params.getNoDisturb())) {
            notification.setNoDisturb(params.getNoDisturb());
        }
        // 是否开启免打扰 通知提醒新增微信公众号需求 新增字段
        if (Objects.nonNull(params.getNoDisturbEnable())) {
            notification.setNoDisturbEnable(params.getNoDisturbEnable());
        }

        try {
            return notificationDao.updateNotificationBySurveyId(notification);
        } catch (Exception e) {
            log.error("[Ticket] update notification failed");
        }
        return null;
    }

    /**
     * 检查是否开启了对应的通知提醒
     *
     * @param noticeType
     * @param notification
     * @return Boolean
     * @author gy.liu
     * @date 2021/8/24
     */
    public static boolean validNotificationIsEnable(Integer noticeType, Notification notification) {
        if (noticeType.equals(NotificationTypeEnum.FIRST_RSPD.getIndex())) {
            return true;
        }
        if (Validator.isNull(notification.getRule())) {
            return false;
        }
        Notification.Rule rule = notification.getRule();
        Boolean valid = false;
        if (noticeType.equals(NotificationTypeEnum.EVERY_RSPD.getIndex())) {
            valid = rule.getEveryRspdEnable();
        } else if (noticeType.equals(NotificationTypeEnum.REACH_RSPD.getIndex())) {
            valid = rule.getReachEnable();
        } else if (noticeType.equals(NotificationTypeEnum.FREQ_RSPD.getIndex())) {
            valid = rule.getFreqEnable();
        } else if (noticeType.equals(NotificationTypeEnum.RATIO_RSPD.getIndex())) {
            valid = rule.getRatioEnable();
        } else if (noticeType.equals(NotificationTypeEnum.QUOTE_FULL.getIndex())) {
            valid = rule.getQuoteFullEnable();
        } else if (noticeType.equals(NotificationTypeEnum.BONUS_AWARD.getIndex())) {
            valid = rule.getAwardBonusEnable();
        } else if (noticeType.equals(NotificationTypeEnum.DRAW_AWARD.getIndex())) {
            valid = rule.getAwardDrawEnable();
        }
        if (Validator.isNull(valid)) {
            return false;
        }
        return valid;
    }

    /**
     * 获取问卷标题， 没有标题则去项目中获取
     *
     * @param notification
     * @return String
     * @author gy.liu
     * @date 2021/8/24
     */
    public String surveyTitle(Notification notification, String surveyTitle) {
        if (StringUtils.isEmpty(surveyTitle)) {
            // 根据问卷id获取问卷项目
            QdesDTO projectDTO = ticketBaseQdesGrpcService.getQdesProject(notification.getSurveyId());
            if (log.isInfoEnabled()) {
                log.info("[Ticket] notifyHelper surveyTitle {}", projectDTO.getTitle());
            }
            if (Objects.nonNull(projectDTO)) {
                surveyTitle = projectDTO.getTitle();
            }
            return StringUtils.isEmpty(surveyTitle) ? "" : surveyTitle;
        }
        return surveyTitle;
    }

    /**
     * 发送通知
     *
     * @param ntype
     * @param notification
     * @param surveyTitle
     * @author gy.liu
     * @date 2021/8/25
     * @date 2022/4/11 16:22 XiaoYunSong 通知提醒新增微信公众号需求 新增 发送微信公众号通知
     */
    public void notifyHelper(Notification notification, String surveyTitle, Integer ntype, String nTypeTag, Long seq) {
        if (log.isInfoEnabled()) {
            log.info("[Ticket] notifyHelper begin notification {}, surveyTitle {},seq{}", notification.getId(), surveyTitle, seq);
        }

        try {
            // 免打扰判断
            boolean isBusy = inCheckDelay(ntype, notification);
            if (isBusy) {
                if (log.isInfoEnabled()) {
                    log.info("[Ticket] 当前通知处于免打扰时间段内，不发送通知 survey_title {}", surveyTitle);
                }
                return;
            }
            // 获取问卷标题
            surveyTitle = surveyTitle(notification, surveyTitle);
            if (StringUtils.isEmpty(surveyTitle)) {
                log.error("[Ticket] notifyHelper surveyTitle is null");
                //return;
            }
            if (Objects.nonNull(notification.getWays()) && Boolean.TRUE.equals(notification.getWays().getEmailEnable())) {
                // 发邮件
                sendEmail(notification, surveyTitle, ntype, nTypeTag, seq);
            }
            if (Objects.nonNull(notification.getWays()) && Boolean.TRUE.equals(notification.getWays().getMobileEnable())) {
                // 发短信
                sendSms(notification, surveyTitle, ntype, nTypeTag, seq);
            }


            // 通知提醒新增微信公众号需求 新增 发送微信公众号通知
            NotificationTypeEnum typeEnum = NotificationTypeEnum.getByIndex(ntype);
            if (Objects.isNull(typeEnum)) {
                log.error("[Ticket] notifyHelper 通知提醒类型错误 {}", ntype);
            } else {
                wechatPublicManager.sendWechatPublicNotification(notification, surveyTitle, typeEnum, nTypeTag, seq);
            }

        } catch (Exception e) {
            log.error("[Ticket] notifyHelper failed:", e);
        }
        if (log.isInfoEnabled()) {
            log.info("[Ticket] notifyHelper end notification {}", notification.getId());
        }
    }


    /**
     * 发送邮件
     *
     * @param notification
     * @author gy.liu
     * @date 2021/8/25
     */
    public void sendEmail(Notification notification, String surveyTitle, Integer nType, String nTypeTag, Long seq) {
        try {
            List<String> receiverAddress = getEmailAddress(notification);
            if (CollectionUtils.isEmpty(receiverAddress)) {
                log.error("[Ticket] notifyHelper sendEmail receive is null");
                return;
            }
            if (Objects.isNull(notification) || StringUtils.isEmpty(notification.getSurveyId())) {
                log.error("[ticket] sendEmail surveyId is null");
                return;
            }
            if (!CollectionUtils.isEmpty(receiverAddress)) {
                EmailContentDTO emailContentDTO = genEmailContent(surveyTitle, nType, notification, nTypeTag, seq);
                if (Objects.isNull(emailContentDTO)) {
                    log.error("[Ticket] notifyHelper sendEmail emailContentDTO is null");
                    return;
                }
                if (log.isInfoEnabled()) {
                    log.info("[Ticket] ticket email notifyHelper emailContentDTO {}", emailContentDTO);
                }
                List<SmtpDTO> smtpDTOS = ticketBaseUserGrpcService.listSmtpByOrgId(notification.getOrgId(), true);
                if (CollectionUtils.isEmpty(smtpDTOS)) {
                    log.error("[Ticket] notifyHelper smtpDTOS is null");
                    return;
                }
                if (log.isInfoEnabled()) {
                    log.info("[Ticket] ticket email notifyHelper listSmtpByOrgId:{}", JSONObject.toJSONString(smtpDTOS));
                }
                List<SmtpDTO> emails = smtpDTOS.stream().filter(SmtpDTO::isNotice).collect(Collectors.toList());
                if (CollectionUtils.isEmpty(emails)) {
                    log.error("[Ticket] notifyHelper 获取默认提醒邮箱失败");
                    return;
                }
                // 发邮件
                notifyUtil.sendEmail(receiverAddress, null, emailContentDTO.getSubject(), emailContentDTO.getContent(), null, emails.get(0));
            }
        } catch (Exception e) {
            log.error("[Ticket] notifyHelper sendEmail 发送邮件异常", e);
        }
    }

    /**
     * 发送短信
     *
     * @param notification
     * @param surveyTitle
     * @param nType
     * @author gy.liu
     * @date 2021/8/26
     */
    public void sendSms(Notification notification, String surveyTitle, Integer nType, String nTypeTag, Long seq) {
        try {
            List<String> receivers = getMobileAddress(notification);
            if (CollectionUtils.isEmpty(receivers)) {
                log.error("[Ticket] notifyHelper sendSms {} receive is null", notification.getId());
                return;
            }
            if (Objects.isNull(notification) || StringUtils.isEmpty(notification.getSurveyId())) {
                log.error("[ticket] sendSms surveyId is null");
                return;
            }
            if (!CollectionUtils.isEmpty(receivers)) {
                String mobileContent = getMobileContentData(surveyTitle, nType, notification, nTypeTag, seq);
                if (StringUtils.isEmpty(mobileContent)) {
                    log.error("[Ticket] notifyHelper sendSms mobileContent is null");
                    return;
                }
                if (log.isInfoEnabled()) {
                    log.info("[Ticket] ticket sendSms notifyHelper mobileContent {}", mobileContent);
                }
                notificationTask.sendNotificationSms(notification.getSurveyId(), receivers, mobileContent, notification.getOrgId());
            }
        } catch (Exception e) {
            log.error("[Ticket] notifyHelper sendSms: 发送短息异常:", e);
        }
    }

    /**
     * 获取邮件收件人邮箱
     *
     * @param notification
     * @return void
     * @author gy.liu
     * @date 2021/8/25
     */
    public List<String> getEmailAddress(Notification notification) {
        List<String> emails = new ArrayList<>();
        if (Objects.nonNull(notification)) {
            Notification.Way way = notification.getWays();
            if (Objects.nonNull(way)) {
                Boolean emailEnable = way.getEmailEnable();
                if (emailEnable) {
                    if (!CollectionUtils.isEmpty(way.getEmails())) {
                        // 去重
                        Set<String> emailSet = new HashSet<>(way.getEmails());
                        emails.addAll(emailSet);
                        return emails;
                    }
                }
            }
        }
        return null;
    }

    /**
     * 获取邮件收件人手机
     *
     * @param notification
     * @return void
     * @author gy.liu
     * @date 2021/8/25
     */
    public List<String> getMobileAddress(Notification notification) {
        List<String> emails = new ArrayList<>();
        Notification.Way way = notification.getWays();
        if (Objects.nonNull(way)) {
            if (way.getMobileEnable()) {
                if (!CollectionUtils.isEmpty(way.getMobiles())) {
                    // 去重
                    Set<String> emailSet = new HashSet<>(way.getMobiles());
                    emails.addAll(emailSet);
                    return emails;
                }
            }
        }
        return null;
    }

    /**
     * 获取邮件内容
     *
     * @param surveyTitle
     * @param nType
     * @param notification
     * @return EmailContentDTO
     * @version v1.0
     * @author gy.liu
     * @date 2021/8/26
     */
    public EmailContentDTO genEmailContent(String surveyTitle, Integer nType, Notification notification, String nTypeTag, Long seq) {
        if (Objects.isNull(notification)) {
            log.error("[Ticket notification is null]");
            return null;
        }
        EmailContentDTO emailContentDTO = new EmailContentDTO();
        if (NotificationTypeEnum.FIRST_RSPD.getIndex().equals(nType) || NotificationTypeEnum.EVERY_RSPD.getIndex().equals(nType)) {
            String subject = String.format("[%s]答卷回收提醒", surveyTitle);
            emailContentDTO.setSubject(subject);
            String smsConetent = getEmailSmsContent(notification, seq);
            if (StringUtils.isEmpty(smsConetent)) {
                log.error("[Ticket genEmailContent smsConetent is null]");
                emailContentDTO.setContent(null);
                return emailContentDTO;
            }
            String content = String.format("您发起的[%s]收到一份成功完成答卷，请点击<br>\n<a class=\"blue\" href=\"%s\" target=\"_blank\">%s</a><br>登陆系统查看", surveyTitle, smsConetent, smsConetent);
            emailContentDTO.setContent(content);
            return emailContentDTO;
        } else if (NotificationTypeEnum.REACH_RSPD.getIndex().equals(nType) && Objects.nonNull(notification.getRule())) {
            Integer descCount = notification.getRule().getReachCount();
            String subject = String.format("[%s]答卷回收提醒", surveyTitle);
            String content = String.format("您发起的[%s]成功完成答卷数达到%s份，请登录系统查看。", surveyTitle, descCount);
            emailContentDTO.setSubject(subject);
            emailContentDTO.setContent(content);
        } else if (NotificationTypeEnum.FREQ_RSPD.getIndex().equals(nType) && Objects.nonNull(notification.getRule())) {
            String time = TIME_OPERATOR_2_TXT.get(notification.getRule().getFreqTime());
            String compare = COMPARE_OPERATOR_2_TXT.get(notification.getRule().getFreqOperator());
            Integer value = notification.getRule().getFreqValue();
            String subject = String.format("[%s]答卷回收提醒", surveyTitle);
            String content = String.format("您发起的[%s]%s成功完成答卷数%s%s份，请登录系统查看。", surveyTitle, time, compare, value);
            emailContentDTO.setSubject(subject);
            emailContentDTO.setContent(content);
        } else if (NotificationTypeEnum.RATIO_RSPD.getIndex().equals(nType) && Objects.nonNull(notification.getRule())) {
            String time = TIME_OPERATOR_2_TXT.get(notification.getRule().getRatioTime());
            String compare = COMPARE_OPERATOR_2_TXT.get(notification.getRule().getRatioOperator());
            Integer value = notification.getRule().getRatioValue();
            String subject = String.format("[%s]答卷回收提醒", surveyTitle);
            String content = String.format("您发起的[%s]%s成功完成答卷数环比%s%s，请登录系统查看。", surveyTitle, time, compare, (value + "%"));
            emailContentDTO.setSubject(subject);
            emailContentDTO.setContent(content);
        } else if (NotificationTypeEnum.QUOTE_FULL.getIndex().equals(nType)) {
            String subject = String.format("[%s]配额提醒", surveyTitle);
            // 获取quote_title
            String quoteTitle = getQuoteTitle(nTypeTag);
            String content = String.format("您发起的[%s]中配额—“%s”已满，请登录系统查看。", surveyTitle, quoteTitle);
            emailContentDTO.setSubject(subject);
            emailContentDTO.setContent(content);
        } else if (NotificationTypeEnum.BONUS_AWARD.getIndex().equals(nType)) {
            // 调用奖励获取award_title
            String awardTitle = getAwardTitle(nTypeTag);
            String subject = String.format("[%s]奖励消耗提醒", surveyTitle);
            String content = String.format("您发起的[%s]微信红包—“%s”已全部发完，请登录系统查看。", surveyTitle, awardTitle);
            emailContentDTO.setSubject(subject);
            emailContentDTO.setContent(content);
        } else if (NotificationTypeEnum.DRAW_AWARD.getIndex().equals(nType)) {
            // 调用奖励获取award_title
            String awardTitle = getAwardTitle(nTypeTag);
            String subject = String.format("[%s]奖励消耗提醒", surveyTitle);
            String content = String.format("您发起的[%s]抽奖奖励—“%s”已全部发完，请登录系统查看。", surveyTitle, awardTitle);
            emailContentDTO.setSubject(subject);
            emailContentDTO.setContent(content);
        }
        return emailContentDTO;
    }

    /**
     * 获取短信内容
     *
     * @param surveyTitle
     * @param nType
     * @param notification
     * @return String
     * @version v1.0
     * @author gy.liu
     * @date 2021/8/26
     */
    public String getMobileContentData(String surveyTitle, Integer nType, Notification notification, String nTypeTag, Long seq) {
        if (NotificationTypeEnum.FIRST_RSPD.getIndex().equals(nType) || NotificationTypeEnum.EVERY_RSPD.getIndex().equals(nType)) {
            String smsConetent = getEmailSmsContent(notification, seq);
            if (StringUtils.isEmpty(smsConetent)) {
                log.error("[Ticket getMobileContentData smsConetent is null]");
                return null;
            }
            return String.format("您发起的[%s]收到一份成功完成答卷，请点击%s  登陆系统查看。", surveyTitle, smsConetent);
        } else if (NotificationTypeEnum.REACH_RSPD.getIndex().equals(nType)) {
            Integer count = notification.getRule().getReachCount();
            return String.format("您发起的[%s]成功完成答卷数达到%s份，请登录系统查看。", surveyTitle, count);
        } else if (NotificationTypeEnum.FREQ_RSPD.getIndex().equals(nType)) {
            String time = TIME_OPERATOR_2_TXT.get(notification.getRule().getFreqTime());
            String compare = COMPARE_OPERATOR_2_TXT.get(notification.getRule().getFreqOperator());
            Integer value = notification.getRule().getFreqValue();
            return String.format("您发起的[%s]%s成功完成答卷数%s%s份，请登录系统查看。", surveyTitle, time, compare, (value + "%"));
        } else if (NotificationTypeEnum.RATIO_RSPD.getIndex().equals(nType)) {
            String time = TIME_OPERATOR_2_TXT.get(notification.getRule().getRatioTime());
            String compare = COMPARE_OPERATOR_2_TXT.get(notification.getRule().getRatioOperator());
            Integer value = notification.getRule().getRatioValue();
            return String.format("您发起的[%s]%s成功完成答卷数环比%s%s，请登录系统查看。", surveyTitle, time, compare, value);
        } else if (NotificationTypeEnum.QUOTE_FULL.getIndex().equals(nType)) {
            // 获取quote_title
            String quoteTitle = getQuoteTitle(nTypeTag);
            return String.format("您发起的[%s]中配额—“%s”已满，请登录系统查看。", surveyTitle, quoteTitle);
        } else if (NotificationTypeEnum.BONUS_AWARD.getIndex().equals(nType)) {
            // 调用奖励获取award_title
            String awardTitle = getAwardTitle(nTypeTag);
            return String.format("您发起的[%s]微信红包—“%s”已全部发完，请登录系统查看。", surveyTitle, awardTitle);
        } else if (NotificationTypeEnum.DRAW_AWARD.getIndex().equals(nType)) {
            // 调用奖励获取award_title
            String awardTitle = getAwardTitle(nTypeTag);
            return String.format("您发起的[%s]抽奖奖励—“%s”已全部发完，请登录系统查看。", surveyTitle, awardTitle);
        }
        return null;
    }

    /**
     * 获取短信内容
     *
     * @return notification
     * @version v1.0
     * @author gy.liu
     * @date 2021/8/23
     */
    public String getEmailSmsContent(Notification notification, Long seq) {
        if (Objects.nonNull(notification)) {
            String surveyId = notification.getSurveyId();
            if (StringUtils.isEmpty(surveyId)) {
                log.error("[ticket] getEmailSmsContent surveyId is null");
                return null;
            }
            // 根据机构id获取机构信息
            //com.bestcem.xm.ticket.grpc.client.dto.user.OrganizationDTO organizationDTO = ticketBaseUserGrpcService.getOrganization(notification.getOrgId());
            //if (log.isInfoEnabled()) {
            //    log.info("[ticket] getEmailSmsContent grpc：param={},surveyId={},resId={}", organizationDTO.getCode(), notification.getSurveyId(), seq);
            //}
            //if (Objects.nonNull(organizationDTO)) {
            //    String orgCode = organizationDTO.getCode();
            //    StringBuilder url = new StringBuilder();
            //    url.append(getCorpUrl(orgCode));
            //    url.append("/record/");
            //    url.append(notification.getSurveyId());
            //    url.append("/reportdetail/");
            //    url.append(seq);
            //    if (log.isInfoEnabled()) {
            //        log.info("[ticket] getEmailSmsContent：url={}", url);
            //    }
            //    return url.toString();
            //}
            StringBuilder url = new StringBuilder();
            url.append(getCorpUrl(""));
            url.append("/record/");
            url.append(notification.getSurveyId());
            url.append("/reportdetail/");
            url.append(seq);
            if (log.isInfoEnabled()) {
                log.info("[ticket] getEmailSmsContent：url={}", url);
            }
            return url.toString();
        }
        return null;
    }

    /**
     * 获取制定公司的域名 orgcode.xxx.com，考虑到私有部署的情况做了一些调整
     *
     * @param orgCode
     * @return String
     * @author gy.liu
     * @date 2021/8/23
     */
    public String getCorpUrl(String orgCode) {
        return notifyProtocol + "://" + notifyUrl;
    }


    /**
     * 配额查询
     *
     * @param nTypeTag
     * @return String
     * @author gy.liu
     * @date 2021/9/2
     */
    @Nullable
    public String getQuoteTitle(String nTypeTag) {
        if (!ObjectId.isValid(nTypeTag)) {
            log.error("[Ticket] getQuoteTitle nTypeTag error {}", nTypeTag);
            return null;
        }
        QuotaCheckItemDTO quotaCheckItemDTO = ticketBaseSurveyGrpcService.getQuotaCheckItem(nTypeTag);
        if (Objects.isNull(quotaCheckItemDTO) || ObjectUtils.isEmpty(quotaCheckItemDTO.getQuotaCondId())) {
            log.error("[Ticket] getQuoteTitle getQuotaCheckItem error {}", quotaCheckItemDTO);
            return null;
        }
        QuotaConditionDTO quotaConditionDTO = ticketBaseSurveyGrpcService.getQuotaCondition(quotaCheckItemDTO.getQuotaCondId());
        if (Objects.isNull(quotaConditionDTO) || ObjectUtils.isEmpty(quotaConditionDTO.getQuotaId())) {
            log.error("[Ticket] getQuoteTitle getQuotaCondition error {}", quotaConditionDTO);
            return null;
        }
        QuotaDTO quotaDTO = ticketBaseQdesGrpcService.getQuota(quotaConditionDTO.getQuotaId());
        if (Objects.isNull(quotaDTO) || ObjectUtils.isEmpty(quotaDTO.getName())) {
            log.error("[Ticket] getQuoteTitle getQuota error {}", quotaDTO);
            return null;
        }
        return quotaDTO.getName();
    }

    /**
     * 奖励查询
     *
     * @param nTypeTag
     * @return String
     * @author gy.liu
     * @date 2021/9/2
     */
    public String getAwardTitle(String nTypeTag) {
        if (!ObjectId.isValid(nTypeTag)) {
            log.error("[Ticket] getAwardTitle nTypeTag error {}", nTypeTag);
            return null;
        }
        return ticketAwardGrpcService.getAwardName(nTypeTag);
    }

    /**
     * 通知提醒触发防打扰时间
     *
     * @return Boolean
     * @author gy.liu
     * @date 2021/8/25
     * @date 2022/4/7 12:16 XiaoYunSong 通知提醒新增微信公众号需求 新增 是否开启免打扰 开关判断
     */
    public Boolean inCheckDelay(Integer ntype, Notification notification) {
        boolean noDisturbEnable = Optional.ofNullable(notification.getNoDisturbEnable()).orElse(true);
        if (!noDisturbEnable) {
            return false;
        }
        LocalDateTime localDateTime = getSendTime(ntype);
        LocalTime sendTime = LocalTime.now();
        if (Objects.nonNull(localDateTime)) {
            sendTime = localDateTime.toLocalTime();
        }
        if (Objects.isNull(notification.getNoDisturb())) {
            return false;
        }
        for (String noDisturb : notification.getNoDisturb()) {
            if (StringUtils.isEmpty(noDisturb)) {
                log.error("[Ticket] inCheckDelay: 防打扰时间未设置");
                return false;
            }
            if (StringUtils.isNotEmpty(noDisturb) && noDisturb.contains("-")) {
                String[] delayTime = noDisturb.split("-");
                if (delayTime.length != 2) {
                    log.error("[Ticket] inCheckDelay: 防打扰时间解析异常");
                    return false;
                }
                String start = delayTime[0];
                String end = delayTime[1];
                if (ObjectUtils.isEmpty(start) || !start.contains(":")
                        || ObjectUtils.isEmpty(end) || !end.contains(":")) {
                    log.error("[Ticket] inCheckDelay 防打扰时间为空");
                    return false;
                }

                String[] temp = new String[]{"00", "00", "00"};
                String[] starts = start.split(":");
                System.arraycopy(starts, 0, temp, 0, starts.length);
                LocalTime startTime = LocalTime.of(Integer.parseInt(temp[0]), Integer.parseInt(temp[1]), Integer.parseInt(temp[2]));

                temp = new String[]{"00", "00", "00"};
                String[] ends = end.split(":");
                System.arraycopy(ends, 0, temp, 0, ends.length);
                LocalTime endTime = LocalTime.of(Integer.parseInt(temp[0]), Integer.parseInt(temp[1]), Integer.parseInt(temp[2]));

                if (log.isInfoEnabled()) {
                    log.info("[Ticket] 通知提醒触发防打扰时间startTime:{},endTime:{}", startTime, endTime);
                }
                if (sendTime.isAfter(startTime) && sendTime.isBefore(endTime)) {
                    return true;
                } else if (sendTime.equals(startTime) || sendTime.equals(endTime)) {
                    return true;
                }
            }
        }
        return false;
    }

    /**
     * 获取发送时间
     *
     * @param type
     * @author gy.liu
     * @date 2021/8/25
     */
    public LocalDateTime getSendTime(Integer type) {
        if (NotificationTypeEnum.FREQ_RSPD.getIndex().equals(type) ||
                NotificationTypeEnum.RATIO_RSPD.getIndex().equals(type)) {
            // 如果是 指定范围内成功完成答卷数达 或 指定范围内成功完成答卷数环比增长 需要定时发送
            // 获取当前日期
            LocalDate localDate = LocalDate.now();
            // 设置时间早晨9:00
            LocalTime localTime = LocalTime.of(PERIOD_NOTIFICATION_TIME.get("hour"), PERIOD_NOTIFICATION_TIME.get("minute"), PERIOD_NOTIFICATION_TIME.get("second"));
            // 获取当前日期时间
            return LocalDateTime.of(localDate, localTime);
        }
        return null;
    }

}
